<?php

namespace app\common\service;
use app\common\service\Order as OrderService;
use app\common\service\Sku as SkuService;
use think\Db;

class Board extends Base
{

    /**
     *
     * @author  huanghuixiang
     * @date 2022/12/9 15:08
     */
    public function getBoardData($address_id){

            $page = 1;
            $limit = 600;//限制600条数据
            $address_id = !empty($address_id)?$address_id:1;
            $where = $data = [];$address_name_show='';$address_id_show=0;
            $order_type=config('mimo.order_type');
            $fei_status=config('mimo.fei_status');
            $break_code_status=config('mimo.break_code_status');
            if(!empty($address_id)){
                $label_list = db("board b")
                    ->field('b.id,b.address_id,b.group_ids,b.label_name,b.factory_ids,b.speed_seting,b.order_type_up,b.break_code_up,ba.address_name')
                    ->join('board_address ba','b.address_id=ba.id','left')
                    ->where(['address_id'=>$address_id,'show_status'=>1])->limit(4)->select();
            }
            //判断是统计工厂的，小组的总产能。将数组的第一个判断是否有值
            $is_factory=0;
            if(isset($label_list[0]['factory_ids']) && !empty($label_list[0]['factory_ids'])){
               $is_factory=1;
            }
            $factoryId=$this->_getFactoryIdList($label_list,$is_factory);

            $skuService = new SkuService();
            foreach ($label_list as $key=>$labelInfo){
                list($where, $whereRaw, $whereHaving, $sql_leftjoin_order_material, $where_material_property,$whereOr) = $this->_searchLabelWhere($labelInfo['id']);
                //订单加一级
               // order_level($where, 'o.');
                $order = "o.caigou_status asc,o.id desc";
                $list = db('order o')
                    ->field("o.id,o.ext_id,o.client_ordernum,o.`status`,o.sku,o.is_auto_import,o.o_type,o.type,o.type_ext
                    ,o.factory_id,o.quantity,o.tail_status,o.break_code_status
                    ,o.shipment_time,o.over_time,o.create_time,o.caigou_over_time,o.caichuang_over_time,o.caichuang_status
                    ,o.chejian_over_time,o.tail_over_time
                    ,o.caigou_status,o.caigou_user_id,su.nick as caigou_user_name,o.caigou_remark,o.remark_approval_color
                    ,o.outgo_status,ftout.name as factory_outgo_name
    ,s.pic,s.ori_pic 
    ,ft.name as factory_name,g.name as group_name
    ,group_concat(distinct os.mid,',', os.size_name,',',os.order_count ,',',os.shicai_count,',',os.jiaohuo_count,',',os.jiaohuo_tail_count,',',os.delivery_count,',',os.daohuo_count  SEPARATOR ';') as order_size_list
    ,min(om.caigou_show) as  caigou_show_min ,max(om.caigou_show) as caigou_show_max
    ,min(om.caigou_status) as caigou_status_min,max(om.caigou_status) as caigou_status_max
    ,min(om.tiaoshu) as tiaoshu_min ,max(om.tiaoshu) as tiaoshu_max
    ,min(om.is_caigou_start) as is_caigou_start_min
    ")
                    ->join('order_material om', "o.id=om.order_id {$sql_leftjoin_order_material}", 'left')
                    ->join('factory ft', "o.factory_id=ft.id", 'left')
                    ->join('factory_outgo ftout', "o.factory_outgo_id=ftout.id", 'left')
                    ->join('group g', "o.group_id=g.id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_user ou ', 'o.id=ou.order_id', 'left')
                    ->join('order_size os ', 'o.id=os.order_id', 'left')
                    ->join('system_user su', "o.caigou_user_id=su.id", 'left')
                    ->join('material m', "om.material_id=m.id", 'left')
                    ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
                    ->where($where)
                    ->where(function($query) use ($whereOr){
                        $query->whereOr($whereOr);
                    })
                    ->whereRaw($whereRaw)
                    ->page($page)->limit($limit)->orderRaw($order)
                    ->group('o.id')
                    ->having($whereHaving)
                    //->fetchSql(true)
                    ->select();

                $count = db('order o')
                    ->join('factory ft', "o.factory_id=ft.id", 'left')
                    ->join('factory_outgo ftout', "o.factory_outgo_id=ftout.id", 'left')
                    ->join('group g', "o.group_id=g.id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_user ou ', 'o.id=ou.order_id', 'left')
                    ->join('order_size os ', 'o.id=os.order_id', 'left')
                    ->join('system_user su', "o.caigou_user_id=su.id", 'left')
                    ->join('order_material om', "o.id=om.order_id {$sql_leftjoin_order_material}", 'left')
                    ->join('material m', "om.material_id=m.id", 'left')
                    ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
                    ->where($where)
                    ->where(function($query) use ($whereOr){
                        $query->whereOr($whereOr);
                    })
                    ->whereRaw($whereRaw)
                    ->group('o.id')
                    ->having($whereHaving)
                    ->count();

                $quantity=0;
                $order_id_array = [];
                foreach ($list as $k => $v) {
                    $quantity +=$v['quantity'];
                    $list[$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
                    $list[$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
                    $list[$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
                    $list[$k]['osList'] = $osList = $this->_deal_order_size_list($v['order_size_list']);
                    $list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
                    $list[$k]['skuStock'] = $skuService->getSkuStockBySku($v['sku'], $v['factory_id']);
                    $list[$k]['ext_id'] = trim($list[$k]['ext_id']);
                    $list[$k]['factory_name'] = trim($list[$k]['factory_name']);
                    $list[$k]['group_name'] = trim($list[$k]['group_name']);
                    $list[$k]['label_name'] = $labelInfo['label_name'];
                    $list[$k]['shipment_time'] = date("m-d",$v['shipment_time']);
                    //完成进度
                    if($v['caichuang_status']==1){
                        $total_data=db('order_user')->where([['order_id', '=', $v['id']]])->field('sum(jianshu) as done_num,fei_status')->select();
                        $list[$k]['fei_show']='';
                        if(isset($total_data[0]['fei_status']) && !empty($total_data[0]['fei_status']) ){
                            $list[$k]['fei_show'] ='【'.$fei_status[$total_data[0]['fei_status']].'--'.round(($total_data[0]['done_num']/$v['quantity'])*100,2).'】';;
                        }
                    }else{
                        $list[$k]['fei_show']='';
                    }
                    //订单类型
                    switch ($v['type_ext']){
                        case "my_return_first":
                            $list[$k]['type'] ="初返";
                            $list[$k]['type_show'] ="my_return_first";
                            break;
                        case "my_first":
                            $list[$k]['type'] ="第一次做";
                            $list[$k]['type_show'] ="my_first";
                            break;
                        default:
                            $list[$k]['type_show'] =$v['type'];
                            $list[$k]['type'] =$order_type[$v['type']];
                    }
                    //断码
                    $list[$k]['break_code_status']='';
                    $list[$k]['break_code_show']='';
                    if($v['tail_status'] !=1){
                        $break_info=db('order_break')->field('size_list')->where([['client_ordernum', '=', $v['client_ordernum']],['sku','=', $v['sku']]])->find();
                        $list[$k]['break_code_show']=$v['break_code_status'];
                        $list[$k]['break_code_status']=isset($break_info['size_list'])?$break_info['size_list']:'';
                    }
                    $order_id_array[] = $v['id'];
                }

                $label_list[$key]['list']=$list;
                $label_list[$key]['count']=$count;
                $label_list[$key]['quantity']=$quantity;

                $address_name_show=$labelInfo['address_name'];
                $address_id_show=$labelInfo['address_id'];
            }

            // 总产能
            $TotalCapacity=$this->_getTotalCapacity($factoryId,$is_factory);
            $data['TotalCapacity'] = $TotalCapacity;
            //展示地址
            $data['address_name'] = $address_name_show;
            $data['address_id'] = $address_id_show;

            $data['data'] = $label_list;
            $data['code'] = 0;
            $data['msg'] = '';

            return $data;

    }
    /**
     * 跟据搜索标签配置搜索条件
     * @author  huanghuixiang
     * return array
     */
    private function _searchLabelWhere($labelid)
    {
        $sql_leftjoin_order_material = "";
        $materialBigWhereSql=[];
        $whereOr=[];
        $whereHaving = '1=1';
        $where_material_property = [];// 物料附加条件
        $whereRaw = ' 1=1 ';
        $where = [
            ["o.status", 'in', [0, 1]],
            ['o.client_status', '<>', 99],
        ];
        $clientOrdernum = '';

        $labelinfo = db("board")->find($labelid);
        if(empty($labelinfo)){
            // echo db()->getLastSql();exit;
        }
        if (!empty($labelinfo)) {
            $HistoryDate = [''=>'','all' => '', 'today' => date("Y-m-d"), 'yestoday' => date("Y-m-d", strtotime("-1 day"))];
            //搜索状态时间起止
            list($start_time, $end_time) = $labelinfo['search_history'] != 'all' ?
                [strtotime(date($HistoryDate[$labelinfo['search_history']] . " 00:00:00")), strtotime(date($HistoryDate[$labelinfo['search_history']] . " " . $labelinfo['search_end_time']))] : ['', ''];
            //当有search_start_time有值的时候，开始时间 优选选择这个

            if(!empty($labelinfo['search_start_time'])){
                $start_time=strtotime($labelinfo['search_start_time']);
            }
            $factory_all = explode(',', $labelinfo['group_ids']); //搜索小组(多个
            $factory_ids = explode(',', $labelinfo['factory_ids']); //搜索工厂(多个
            $material_status_arr = explode(',', $labelinfo['search_data_status']); //搜索物料状态(多个
            $material_property = $labelinfo['search_materal_type']; //搜索物料类型
            $material_status_logic = $labelinfo['m_status_logic'];
        }

        if ($clientOrdernum != '') {
            $where[0] = ["1", '=', 1];//清["o.status", 'in', [0, 1]],这个条件
            $where[1] = ["1", '=', 1];
            $where[] = ['o.client_ordernum', '=', $clientOrdernum];
        }
        //单类
        if($labelinfo['order_type'] != ''){
            if($labelinfo['order_type']=='my_return_first' ||  $labelinfo['order_type']=='my_first'){//返单第一次、第一次做
                $where[] = ['o.type_ext', '=', $labelinfo['order_type']];
            }else{
                $where[] = ['o.type', '=', $labelinfo['order_type']];
            }
        }

        //小组
        if (!empty($factory_all[0])) {
            foreach ($factory_all as $k => $v) {
                $factory_all[$k] = intval($v);
            }
            $where[] = ['o.group_id', 'in', $factory_all];
        }
        //工厂
        if(!empty($factory_ids[0])){
            foreach ($factory_ids as $k => $v) {
                $factory_ids[$k] = intval($v);
            }
            $where[] = ['o.factory_id', 'in', $factory_ids];
        }
        //断码
        if(!empty($labelinfo['break_code_status'])){
            $where[] = ['o.break_code_status', '=', $labelinfo['break_code_status']];
        }

        //剩余出货天数
        if(!empty($labelinfo['shipment_day'])){
            $shipment=explode(',',$labelinfo['shipment_day']);
            foreach ($shipment as $value){
                $dayEnd = strtotime("+{$value} day 00:00:00");
                $dayStart = strtotime(date("Y-m-d",time())." 00:00:00");
                $whereOr[]=['o.shipment_time', 'between', [$dayStart, $dayEnd]];
            }
        }
        //订单状态   --时间段
        if (!empty($labelinfo['order_status'])) {
            switch ($labelinfo['order_status']){
                case 1:
                    $where[] = ['o.caigou_status', '=', 0];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.create_time', 'between', [$start_time, $end_time]];
                    }
                    break;
                case 2:
                    $where[] = ['o.caigou_status', '=', 1];
                    $where[] = ['o.caichuang_status', '=', 0];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.caigou_over_time', 'between', [$start_time, $end_time]];
                    }
                    break;
                case 3:
                    $where[] = ['o.caichuang_status', '=', 1];
                    $where[] = ['o.chejian_status', '=', 0];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.caichuang_over_time', 'between', [$start_time, $end_time]];
                    }
                    break;
                case 4:
                    $where[] = ['o.chejian_status', '=', 1];
                    $where[] = ['o.tail_status', '=', 0];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.chejian_over_time', 'between', [$start_time, $end_time]];
                    }
                    break;
                case 5:
                    $where[] = ['o.tail_status', '=', 1];
                    $where[] = ['o.real_shipment_status', '=', 0];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.tail_over_time', 'between', [$start_time, $end_time]];
                    }
                    break;
                case 6:
                    $where[] = ['o.real_shipment_status', '=', 1];
                    $where[] = ['o.status', '=', 1];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.real_shipment_time', 'between', [$start_time, $end_time]];
                    }
                    break;
                case 7:
                    $where[] = ['o.status', '=', 2];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.over_time', 'between', [$start_time, $end_time]];
                    }
                    break;
                case 99:
                    $where[] = ['o.status', '=', 99];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.client_status_del_time', 'between', [$start_time, $end_time]];
                    }
                    break;
                case 999:
                    $where[] = ['o.status', '=', 999];
                    if(!empty($start_time) && !empty($end_time)){
                        $where[] = ['o.client_status_del_time', 'between', [$start_time, $end_time]];
                    }
                    break;
            }
        }
        $oldWhere = $where; //清空where参数存新值

        //***************分界线*********************/
        //如果有物料的筛选
        if(!empty($material_status_arr[0])){
            $where[]=  ['om.caigou_show', '>', 0];

            if(!in_array('17',$material_status_arr)){//不是搜索已经生产（裁车尾)的订单
                $where[] = ['o.caichuang_status', '=', 0];
                $where[] = ['o.chejian_status', '=', 0];
            }else{ //去尾货
                $whereRaw .= " and ( o.caichuang_over_time <> o.chejian_over_time) ";
            }
            //搜索物料类型
            switch ($labelinfo["search_materal_type"]) {
                case 2://铺料
                    $where[] = ['m.type', '=', "accessories"];
                    $where_material_property[] = ['m.type', '=', "'accessories'"];
                    break;
                case 1://面料
                    $where[] = ['m.type', '<>', "accessories"];
                    $where_material_property[] = ['m.type', '<>', "'accessories'"];
            }
            //$sql_leftjoin_order_material=$this->_createLeftJoinSql($labelinfo["search_materal_type"],$material_status_arr);
            $timewhere_arr = [
                1 => " o.create_time between " . $start_time . " and " . $end_time //未采购 取下单时间
                , 2 => " om.caigou_start_time between " . $start_time . " and " . $end_time //采购中 取开始采购时间
                , 3 => " om.tiaoshu_status_time between " . $start_time . " and " . $end_time //换料中 取换料时间
                , 4 => " om.arrive_time between " . $start_time . " and " . $end_time //已到料 取到料时间
                , 5 => " om.arrive_time between " . $start_time . " and " . $end_time  //未批色 取到料时间
                , 6 => " om.caigou_first_time between " . $start_time . " and " . $end_time //批色不通过 取批色不通时间
                , 7 => " om.caigou_over_time between " . $start_time . " and " . $end_time //已批色 取批色完成时间
                , 8 => " om.caigou_over_time between " . $start_time . " and " . $end_time //已批色齐套 同上
                , 9 => " om2.caigou_over_time between " . $start_time . " and " . $end_time //批色未齐套 取子查询的批色完成时间
                , 10 => " om2.caigou_finish_time between " . $start_time . " and " . $end_time //未购未齐套  取采购完成时间
                , 11 => " om.caigou_finish_time between " . $start_time . " and " . $end_time //未购已齐套 同上
                , 12 => " om.caigou_finish_time between " . $start_time . " and " . $end_time //可裁剪 同上
                , 13 => " 1=1 " //未发货 需求说及不用与其它状态关联
                , 14 => " om.send_goods_time between " . $start_time . " and " . $end_time //已发货
                , 15 => " om.send_goods_time between " . $start_time . " and " . $end_time //发货未齐套
                , 16 => " om.send_goods_time between " . $start_time . " and " . $end_time //发货已齐套
                , 17 => " 1=1 " //已裁床/车缝/后整
                , 18 => " 1=1 "
                , 19 => " 1=1 "
                , 20 => " 1=1 "
            ];


            $oldMaterialWhere = $where_material_property;
            $bigWhereSql = $materialBigWhereSql = '';
            $searchTimeWhere = [];

            foreach ($material_status_arr as $index => $material_status) {
                $where = $where_material_property = [];
                switch ($material_status) {
                    case 1://未采购
                        $where[] = ['om.is_caigou_start', '=', 0];
                        $where_material_property[] = ['om.is_caigou_start', '=', 0];
                        break;
                    case 2://采购中
                        $where[] = ['om.is_caigou_start', '=', 1];
                        $where_material_property[] = ['om.is_caigou_start', '=', 1];
                        break;
                    case 3://换料中
                        $where[] = ['om.tiaoshu_status', '=', 10];
                        $where_material_property[] = ['om.tiaoshu_status', '=', 10];
                        $where_material_property[] = ['om.return_notconfirm', '=', 0];
                        break;
                    case 4://已到料 含义：按了到料，不要换料中
                        $where[] = ['om.arrive_time', '>', 0];
                        //$where[] = ['om.is_caigou_start', '<', 2];
                        $where_material_property[] = ['om.arrive_time', '>', 0];
                        //$where_material_property[] = ['om.is_caigou_start', '<', 2];
                        $where_material_property[] = ['om.tiaoshu_status', '<>', 10];
                        break;
                    case 13://未发货
                        $where[] = ['om.send_goods_status', '=', 0];
                        $where_material_property[] = ['om.send_goods_status', '=', 0];
                        break;
                    case 14://已发货
                        $where[] = ['om.send_goods_status', '=', 1];
                        $where_material_property[] = ['om.send_goods_status', '=', 1];
                        break;
                    case 5://未批色
                        $where[] = ['om.caigou_status', '=', 0];
                        $where_material_property[] = ['om.caigou_status', '=', 0];
                        break;
                    case 6://批色不通过
                        $where[] = ['om.caigou_status', '=', 2];
                        $where_material_property[] = ['om.caigou_status', '=', 2];
                        break;
                    case 7://已批色
                        $where[] = ['om.caigou_status', '=', 1];
                        $where_material_property[] = ['om.caigou_status', '=', 1];
                        break;
                    case 8://已批色齐套  不包括：已完成裁床以后的订单
                        $where[] = ['om.caigou_status', '=', 1];
                        $where[] = ['m.type', '<>', "'accessories'"];
                        $sql = "select min(om2.caigou_status) as caigou_status_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories' ";
                        $sql2 = "select max(om2.caigou_status) as caigou_status_max
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories' ";
                        $sql_leftjoin_order_material = " and 1=($sql) and 1=($sql2)";
                        break;
                    case 9://批色未齐套
                        $where[] = ['om.caigou_status', '<>', 1];
                        //$where[] = ['m.type', '<>', "'accessories'"];
                        $sql = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' ";
                        $piSeOverTime = $labelinfo['search_history'] != 'all' ? " and " . $timewhere_arr[$material_status] : '';
                        $sql1 = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' and om2.caigou_status=1" . $piSeOverTime; //已批色大于0
                        $sql_leftjoin_order_material = " and ($sql1)>0 and 1<($sql)  and ($sql)>($sql1)    ";
                        break;
                    case 10://采购未齐套 有一个采购完成
                        $where[] = ['om.is_caigou_start', '<>', 2];
                        $sql = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                        $caigouOverTime = $labelinfo['search_history'] != 'all' ? " and " . $timewhere_arr[$material_status] : '';
                        $sql1 = "select max(om2.is_caigou_start) as is_caigou_start_max
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  " . $caigouOverTime;
                        $sql2 = "select min(om2.is_caigou_start) as is_caigou_start_min
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                        $sql_leftjoin_order_material = " and 1<($sql)  and 2=($sql1) and 2>($sql2)  ";
                        break;
                    case 11://采购已齐套 定义：只要全部物料是“采购完成”状态  或  或中有一个是“可裁剪”+其它全是“采购完成 ”
                        $whereRaw .= " and ( o.caichuang_can_do <> 1 OR o.caichuang_status <>0)";//与12 切开
                        $where[] = ['om.is_caigou_start', '=', 2];
                        $where[] = ['om.tiaoshu_status', '<>', 10];//
                        $sql = "select min(om2.is_caigou_start) as is_caigou_start_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                        $sql2 = "select max(om2.is_caigou_start) as is_caigou_start_max
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                        $sql3 = "select IFNULL(max(om2.tiaoshu_status), 0) 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.tiaoshu_status=10 ";
                        $sql_leftjoin_order_material = " and 2=($sql) and 2=($sql2) and  10<>($sql3) ";
                        break;
                    case 12://可裁剪 与以前的 未裁剪完成一样。
                        $where[] = ['o.caichuang_can_do', '=', 1];
                        $where[] = ['o.caichuang_status', '=', 0];
                        $sql = "select min(om2.caichuang_can_do)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' and om2.return_notconfirm=0 ";
                        $sql_leftjoin_order_material = " and ($sql)>0";
                        break;
                    case 15://发货未齐套 //1与0的互相作用肯定物料数>=2样以上。
                        $where[] = ['om.send_goods_status', '=', 1];
                        $sql1 = "select min(om2.send_goods_status)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
//                    $sql_leftjoin_order_material = " and 1<($sql)  and 0=($sql1)  ";
                        $sql_leftjoin_order_material = " and 0=($sql1)  ";
                        break;
                    case 16://发货已齐套
                        $where[] = ['om.send_goods_status', '=', 1];
                        $sql = "select min(om2.send_goods_status)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                        $sql_leftjoin_order_material = " and 1=($sql)  ";
                        break;
                    case 17://已裁床/车缝/已后整  一般 已生产但未买齐的记录
                        $where[] = ['1', '=', 1];
                        $whereRaw .= " and ( o.caichuang_status= 1 OR o.chejian_status=1 OR o.tail_status=1 ) and real_shipment_status=0 ";//
                        //$sql_leftjoin_order_material = " and 1=1  ";
                        break;
                    case 18://已打标
                        $where[] = ['om.tiaoshu_detail', '<>', "''"];
                        $where_material_property[] = ['om.tiaoshu_detail', '<>', "''"];
                        break;
                    case 19://退料待审核
                        $where[] = ['om.return_notconfirm', '=', 1];
                        break;
                    case 20://占用已出库
                        $where[] = ['om.stock_checkout_state', '=', 1];
                        break;

                }
                if ($timewhere_arr[$material_status] != " 1=1 " && !in_array($material_status, [9, 10])) {
                    $searchTimeWhere[] = $timewhere_arr[$material_status];
                }

                //处理订单搜索条件
                $whereSql = '';
                foreach ($where as $key => $whereitem) {
                    $whereSql .= implode(' ', $whereitem) . " and ";
                }
                $whereSql = trim($whereSql, " and ");
                if ($material_status_logic == 'and') { //多个物料状态搜索是并且关系
                    $bigWhereSql .= " and (" . $whereSql . ")";
                } else {
                    if (in_array($material_status, [9, 10])) { //采购/批色未齐套 时，不用在未批色的结果里拼接采购/批色完成时间， 批色完成时间放到【查询有批色结果】的子查询里
                        $bigWhereSql .= " or (" . $whereSql . ")";
                    } else {
                        $bigWhereSql .= $labelinfo['search_history'] != 'all' ? " or (" . $whereSql . " and " . $timewhere_arr[$material_status] . ")" : " or (" . $whereSql . ")";//拼接时间条件
                    }
                }
                //处理物料搜索逻辑
                $material_status_whereSql = '';
                $where_material_property = array_merge($where_material_property, $oldMaterialWhere);
                foreach ($where_material_property as $key => $whereitem) {
                    $material_status_whereSql .= implode(' ', $whereitem) . " and ";
                }
                $material_status_whereSql = trim($material_status_whereSql, " and ");

                if ($material_status_logic == 'and') { //多个物料状态搜索是并且关系
                    $materialBigWhereSql .= $material_status_whereSql != '' ? " and (" . $material_status_whereSql . ")" : '';
                } else {
                    $materialBigWhereSql .= $material_status_whereSql != '' ? " or (" . $material_status_whereSql . ")" : '';
                }
            }
            if ($material_status_logic == 'and' && count($searchTimeWhere) > 0) { //查询各状态时间点最近的记录
                $searchTimeWhereSql = implode(' or ', $searchTimeWhere);
                $bigWhereSql .= $labelinfo['search_history'] != 'all' ? " and (" . $searchTimeWhereSql . ")" : '';//拼接时间条件
            }
            $bigWhereSql = trim($bigWhereSql, " or ");
            $materialBigWhereSql = trim($materialBigWhereSql, " or ");//物料表里的或查询
            $bigWhereSql = trim($bigWhereSql, " and ");
            $materialBigWhereSql = trim($materialBigWhereSql, " and ");

            $materialBigWhereSql = $materialBigWhereSql != '' ? $materialBigWhereSql : [];//物料表里的或查询
            $whereRaw = $whereRaw . " and " . $bigWhereSql;
        }

        return [
            $oldWhere,
            $whereRaw,
            $whereHaving,
            $sql_leftjoin_order_material,
            $materialBigWhereSql,
            $whereOr,
        ];
    }
    /*
    * 对工厂小组id进行：拼接、去重
     * @author  huanghuixiang
     * @parm $is_factory=1 为统计工厂总产，0为小组总产能
    */
    public function  _getFactoryIdList($label_list,$is_factory){
        $factory_ids_str='';
        if($is_factory==1){
            foreach ($label_list as $info){
                foreach ($label_list as $info){
                    $factory_ids_str .=$info['factory_ids'];
                }
            }
        }else{
            foreach ($label_list as $info){
                $factory_ids_str .=$info['group_ids'];
            }
        }

        $factory_ids =array_unique(explode(',',$factory_ids_str));
        $factoryIdList='';
        $end_num=count($factory_ids)-1;

        $i=0;
        foreach ($factory_ids as $key=>$info){
            //数组中最后一个数不用逗号
            if($i==$end_num){
                $factoryIdList .=$info;
            }else{
                $factoryIdList .=$info.',';
            }
            $i++;
        }
        return $factoryIdList;
    }

    /*
     * 总产能
     * @author  huanghuixiang
     * @parm  $is_factory=1 统计工厂，$is_factory=0 统计小组
     */
    public function _getTotalCapacity($factoryId,$is_factory){
        $from = 0;
        $capacity=0;
        $today_start=strtotime(date("Y-m-d",time()).' 00:00:00');
        $today_end=strtotime(date("Y-m-d",time()).' 23:59:59');
        $orderService = new OrderService();

        //7日平均日产能
        $cacheSuffix =  (-100).'-' . str_replace(',', '_', $factoryId) . '-' . $from;
        $output7Arr = cache(STAT_OUTPUT_AVG7 . $cacheSuffix);

        if (empty($output7Arr)) $output7Arr = $orderService->getOutputByDays(7, $factoryId, $from);
        cache(STAT_OUTPUT_AVG7 . $cacheSuffix, $output7Arr, 1800);//86400

        //当天总加工费
        if(!empty($factoryId) && !empty($today_start) && !empty($today_end) ){
            if($is_factory==1){
                $select_sql=' o.group_id in('.$factoryId.') ';
            }else{
                $select_sql=' o.factory_id in('.$factoryId.') ';
            }
            $sql = "SELECT   sum(o.order_price* IFNULL(o.quantity, 0)) as sum_fob_price
                ,sum(IFNULL(oext.cost_profit,0) * IFNULL(o.quantity, 0)) as sum_cost_price
                FROM wx_order o
                LEFT JOIN wx_order_ext oext on (o.id=oext.order_id)
                where 
                o.status in (0,1,2)  and  {$select_sql}
                and o.create_time>={$today_start} and o.create_time <= {$today_end}";

            $temp = db::query($sql);

            //总产能=当天总加工费÷7日平均日产能金额
            if(!empty($output7Arr['avgMoney'])){
                $capacity=  ($temp[0]['sum_cost_price'])/$output7Arr['avgMoney'];
            }
        }

        return round($capacity*100,2);
    }


    public function _deal_order_size_list($order_size_list)
    {
        if (trim($order_size_list) == '') {
            return [];
        }
        $res = [];
        $list = explode(';', $order_size_list);
        foreach ($list as $k => $v) {
            $temp = explode(',', $v);
            $res[] = [
                'size_name' => $temp[1],
                'order_count' => $temp[2],
                'shicai_count' => $temp[3],
                'jiaohuo_count' => $temp[4],
                'jiaohuo_tail_count' => $temp[5],
                'delivery_count' => $temp[6],
                'daohuo_count' => $temp[7],
            ];
        }
        return $res;
    }

}